package com.symaster.gameengine.core;

import org.lwjgl.glfw.GLFW;

import java.util.concurrent.TimeUnit;


/**
 * OpenGL高刷, 基础Canvas
 *
 * @author yinmiao
 * @since 2024/9/15
 */
public abstract class Canvas {
    private float targetFPS;
    private EngineFrame engineFrame;

    public Canvas() {
        this.targetFPS = 120;
    }

    public final float getTargetFPS() {
        return targetFPS;
    }

    public final void setTargetFPS(float targetFPS) {
        this.targetFPS = targetFPS;
    }

    public final EngineFrame getEngineFrame() {
        return engineFrame;
    }

    public final void setEngineFrame(EngineFrame engineFrame) {
        this.engineFrame = engineFrame;
    }

    public abstract void loop(long window, int initWindowWidth, int initWindowHeight);

    public abstract void resourceLoad();

    protected void nextFrame(long window, double startTime) {
        // 目标帧时间（以秒计）
        double frameTime = 1.0 / this.getTargetFPS();

        // 交换颜色缓冲区
        GLFW.glfwSwapBuffers(window);
        // 轮询事件
        GLFW.glfwPollEvents();
        // 等待平滑帧
        this.fpsSmooth(GLFW.glfwGetTime(), startTime, frameTime);
    }

    private void fpsSmooth(double endTime, double startTime, double frameTime) {
        // 计算渲染一帧的实际时间
        double deltaTime = endTime - startTime;

        // 如果实际渲染时间小于目标帧时间，则睡眠
        if (deltaTime < frameTime) {
            try {
                TimeUnit.MILLISECONDS.sleep((long) ((frameTime - deltaTime) * 1000));
            } catch (InterruptedException ignored) {
            }
        }
    }
}
